package com.baidu.health.service;

import com.baidu.health.mapper.TbOrderItemMapper;
import com.baidu.health.mapper.TbOrdertestMapper;
import com.baidu.health.pojo.TbOrderItem;
//import com.baidu.health.pojo.TbOrdertest;
import com.baidu.health.util.Result;
import com.baidu.health.util.ResultResponse;
import com.github.wxpay.sdk.WXPayUtil;
import okhttp3.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: 孙新超
 *
 * @author 孙新超
 * @version 1.0
 * @date To change this template use File | Settings | File Templates.
 * @date
 */
@Service
public class WxPayServiceImpl implements WxPayService{
    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private TbOrdertestMapper mapper;
    @Resource
    private TbOrderItemMapper itemMapper;
    int vxpay = 0;
    @Override
    public Result unifiedOrder(Long orderId, Integer totolFee, String body) throws Exception {
        OkHttpClient okHttpClient=new OkHttpClient();
        //设置解析格式
        MediaType mediaType = MediaType.parse("application/xml");
        //准备接口参数
        Map<String,String> map=new HashMap<>();
        map.put("appid",appid);//公众号ID
        map.put("mch_id",partner);//商户号
        map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        //map.put("sign",)
        map.put("body",body);//商品描述
        map.put("out_trade_no",orderId.toString());//订单号
        map.put("total_fee",totolFee.toString());//标价金额
        map.put("spbill_create_ip","127.0.0.1");//终端IP
        map.put("notify_url",notifyurl);//通知地址
        map.put("trade_type","NATIVE");
        //
        String content = WXPayUtil.generateSignedXml(map, partnerkey);
        //
        RequestBody requestBody=RequestBody.create(mediaType,content);
        //创建request
        Request request=new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/unifiedorder")
                .post(requestBody)
                .build();
        //获取call对象 call可以同步调用,也可以异步调用
        Call call = okHttpClient.newCall(request);
        //同步发送http请求返回响应
        Response execute = call.execute();

        int code = execute.code();
        String protocol = execute.protocol().toString();
        ResponseBody responseBody = execute.body();
        String response_xml = responseBody.string();
        System.out.println("code"+code);
        System.out.println("protocol"+protocol);
        System.out.println("response_xml"+response_xml);
        //解析
        /*Document document = DocumentHelper.parseText(response_xml);

        Element rootElement = document.getRootElement();
        Element code_url = rootElement.element("code_url");
        String stringValue = code_url.getStringValue();*/
        Map<String, String> xmlToMap = WXPayUtil.xmlToMap(response_xml);
        String code_url = xmlToMap.get("code_url");
        return new Result(true,"1",code_url);
    }

    @Override
    public Result wxOrderquery(Long orderId) throws Exception {
        //1.创建okhttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
        MediaType mediaType=MediaType.parse("application/xml");
        //3.准备接口参数
        Map<String,String> map=new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("out_trade_no",orderId.toString());
        map.put("nonce_str",WXPayUtil.generateNonceStr());
        //通过签名算法计算得出的签名值
        String content = WXPayUtil.generateSignedXml(map, partnerkey);
        //
        RequestBody requestBody=RequestBody.create(mediaType,content);
        //创建request
        Request request=new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/orderquery")
                .post(requestBody)
                .build();
        //获取call对象
        Call call = okHttpClient.newCall(request);
        //同步发送http请求  返回响应
        Response response = call.execute();

        //请求中的信息
        int code = response.code();
        String message = response.message();
        String protocol = response.protocol().toString();
        System.out.println("code"+code);
        System.out.println("message"+message);
        System.out.println("protocol"+protocol);
        //获取响应
        ResponseBody body = response.body();
        String body_xml = body.string();
        System.out.println("body_xml==>"+body_xml);
        //将xml格式转换为map
        Map<String, String> xmlToMap = WXPayUtil.xmlToMap(body_xml);
        //获取返回状态码
        String return_code = xmlToMap.get("return_code");
        if (!StringUtils.isEmpty(return_code) && return_code.equals("SUCCESS")){
            String result_code = xmlToMap.get("result_code");//业务结果
            String trade_state = xmlToMap.get("trade_state");//交易状态
            String trade_state_desc = xmlToMap.get("trade_state_desc");//交易状态描述
            /**
             * SUCCESS--支付成功
             * REFUND--转入退款
             * NOTPAY--未支付
             * CLOSED--已关闭
             * REVOKED--已撤销(刷卡支付)
             * USERPAYING--用户支付中
             * PAYERROR--支付失败(其他原因，如银行返回失败)
             * ACCEPT--已接收，等待扣款
             */
            if (!StringUtils.isEmpty(result_code) && result_code.equals("SUCCESS")
                    && !StringUtils.isEmpty(trade_state) && trade_state.equals("SUCCESS")){
                //支付成功 1.修改订单状态为已支付  2.用户增加相应的积分
                System.out.println("支付成功 1.修改订单状态为已支付  2.用户增加相应的积分");
                //支付完成之后进行加积分
                vxpay=vxpay+1;
                if(vxpay==1){
                    HashMap<Object, Object> mqmap = new HashMap<>();
                    String total_fee=xmlToMap.get("total_fee");
                    Integer inttotal_fee = Integer.parseInt(total_fee);
                    mqmap.put("num",inttotal_fee*100);
                    TbOrderItem order = itemMapper.selectById(orderId);
                    mqmap.put("goods_id",order.getGoodsId());
                    rabbitTemplate.convertAndSend("","Queue_lyp",  mqmap);
                }
                return new Result(true,"1",trade_state_desc);
            }else {
                return new Result(false,"0",trade_state_desc);
            }
        }
        return new Result(false,"0","执行失败");
    }
}
